#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/9/17 18:18
# @Author  : youfeng
import threading

from beanstalkc import SocketError

from config.beanstalk_conf import OnlineBeanstalkConfig, OnlineTubeConfig
from common.pybeanstalk import PyBeanstalk


class MQHandler(object):

    def __init__(self, log):
        self.log = log
        self.__beanstalk = PyBeanstalk(OnlineBeanstalkConfig.HOST, OnlineBeanstalkConfig.PORT)
        self.__lock = threading.Lock()

    # 判断消息队列是否堵住了
    def __is_mq_block(self, output_tube, block_size):
        try:
            count = self.__beanstalk.get_tube_count(output_tube)
        except Exception as e:
            if isinstance(e.args, tuple) and len(e.args) == 3 and e.args[1] == 'NOT_FOUND':
                count = 0
            else:
                self.log.info(type(e.args))
                self.log.error('获取当前队列数目失败..开启消息队列休眠...')
                self.log.exception(e)
                count = block_size

        if count >= block_size:
            return True

        return False

    # 判断工商队列是否堵住
    def is_gsxt_block(self):
        return self.__is_mq_block(OnlineTubeConfig.TUBE_GSXT, OnlineTubeConfig.BLOCK_SIZE_GSXT)

    # 判断文书队列是否堵住
    def is_wenshu_block(self):
        return self.__is_mq_block(OnlineTubeConfig.TUBE_WENSHU, OnlineTubeConfig.BLOCK_SIZE_WENSHU)

    # 判断新闻队列是否堵住
    def is_news_block(self):
        return self.__is_mq_block(OnlineTubeConfig.TUBE_NEWS, OnlineTubeConfig.BLOCK_SIZE_NEWS)

    # 判断执行采集是否堵住
    def is_zhixing_block(self):
        return self.__is_mq_block(OnlineTubeConfig.TUBE_ZHIXING, OnlineTubeConfig.BLOCK_SIZE_ZHIXING)

    # 判断失信采集是否堵住
    def is_shixin_block(self):
        return self.__is_mq_block(OnlineTubeConfig.TUBE_SHIXIN, OnlineTubeConfig.BLOCK_SIZE_SHIXIN)

    def __send_request(self, msg, tube):

        # 发消息队列要加锁
        with self.__lock:
            try:
                self.__beanstalk.put(tube, str(msg))
            except SocketError as e:
                self.__beanstalk.reconnect()
                self.log.warn("reconnect beanstalk...")
                self.log.exception(e)
                return False
            except Exception as e:
                self.log.error('消息队列异常: ')
                self.log.exception(e)
                return False

        return True

    # 发送工商采集消息
    def send_gsxt_request(self, company):
        return self.__send_request(company, OnlineTubeConfig.TUBE_GSXT)

    # 发送文书采集消息
    def send_wenshu_request(self, company):
        return self.__send_request(company, OnlineTubeConfig.TUBE_WENSHU)

    # 发送执行采集消息
    def send_zhixing_request(self, company):
        return self.__send_request(company, OnlineTubeConfig.TUBE_ZHIXING)

    # 发送失信采集消息
    def send_shixin_request(self, company):
        return self.__send_request(company, OnlineTubeConfig.TUBE_SHIXIN)

    # 发送新闻采集消息
    def send_news_request(self, company):
        return self.__send_request(company, OnlineTubeConfig.TUBE_NEWS)
